<script setup lang="ts" name="SystemSmsLog">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { getIntDictOptions, getDictLabel } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { dateTimeFormatter, formatDate } from '@/utils/dateUtil'
import { dataToFile } from '@/components/Excel/src/helper'
import { SmsLogApi, SmsLogType } from '@/api/system/messages/sms/log'
import { SmsChannelApi, SmsChannelType } from '@/api/system/messages/sms/channel'
import SmsLogDetail from './SmsLogDetail.vue'
import { checkPermit } from '@/utils/permit'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const { t } = useI18n() // 国际化
const total = ref(0) // 列表的总页数
const list = ref([]) // 表格数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const queryParams = ref({
  pageIndex: 1,
  pageSize: 20,
  mobile: undefined,
  channelId: undefined,
  templateId: undefined,
  sendStatus: undefined,
  sendTime: [],
  receiveStatus: undefined,
  receiveTime: [],
})
const queryFormRef = ref() // 搜索的表单
const channelList = ref<SmsChannelType[]>([]) // 短信渠道列表
const isExpanded = ref(false) // 查询条件折叠展开

const expandChange = () => {
  isExpanded.value = !isExpanded.value
}


/** 查询列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await SmsLogApi.page(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageIndex = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageIndex: 1,
    pageSize: 20,
    mobile: undefined,
    channelId: undefined,
    templateId: undefined,
    sendStatus: undefined,
    sendTime: [],
    receiveStatus: undefined,
    receiveTime: [],
  }
  handleQuery()
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (data: SmsLogType) => {
  detailRef.value.open(data)
}

const ExcelExportDialogRef = ref()

const filedList = ref([
  { key: 'id', value: 'ID' },
  { key: 'channelId', value: t('sys.messages.sms.log', 'channelId') },
  { key: 'channelCode', value: t('sys.messages.sms.log', 'channelCode') },
  { key: 'templateId', value: t('sys.messages.sms.log', 'templateId') },
  { key: 'templateCode', value: t('sys.messages.sms.log', 'templateCode') },
  { key: 'templateType', value: t('sys.messages.sms.log', 'templateType') },
  { key: 'templateContent', value: t('sys.messages.sms.log', 'templateContent') },
  { key: 'templateParams', value: t('sys.messages.sms.log', 'templateParams') },
  { key: 'apiTemplateId', value: t('sys.messages.sms.log', 'apiTemplateId') },
  { key: 'mobile', value: t('sys.messages.sms.log', 'mobile') },
  { key: 'userId', value: t('sys.messages.sms.log', 'userId') },
  { key: 'userType', value: t('sys.messages.sms.log', 'userType') },
  { key: 'sendStatus', value: t('sys.messages.sms.log', 'sendStatus') },
  { key: 'sendTime', value: t('sys.messages.sms.log', 'sendTime') },
  { key: 'apiSendCode', value: t('sys.messages.sms.log', 'apiSendCode') },
  { key: 'apiSendMsg', value: t('sys.messages.sms.log', 'apiSendMsg') },
  { key: 'apiRequestId', value: t('sys.messages.sms.log', 'apiRequestId') },
  { key: 'apiSerialNo', value: t('sys.messages.sms.log', 'apiSerialNo') },
  { key: 'receiveStatus', value: t('sys.messages.sms.log', 'receiveStatus') },
  { key: 'receiveTime', value: t('sys.messages.sms.log', 'receiveTime') },
  { key: 'apiReceiveCode', value: t('sys.messages.sms.log', 'apiReceiveCode') },
  { key: 'apiReceiveMsg', value: t('sys.messages.sms.log', 'apiReceiveMsg') },
  { key: 'create_time', value: t('common', 'createTime') },
])
/** 导出按钮操作 */
const handleExport = async () => {
  ExcelExportDialogRef.value.open()
}

const exportDone = async (res) => {
  if (res.dataScope === 1) {
    dataToFile(list.value, res)
  } else if (res.dataScope === 3) {
    const allList = await SmsLogApi.export(queryParams.value)
    dataToFile(allList, res)
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载渠道列表
  channelList.value = await SmsChannelApi.simple()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('sys.messages.sms.log', 'mobile')" prop="mobile" class="!w-240px">
            <el-input v-model="queryParams.mobile" :placeholder="t('sys.messages.sms.log.rules', 'mobile')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem :label="t('sys.messages.sms.log', 'channel')" prop="channelId">
            <el-select v-model="queryParams.channelId" class="!w-160px" filterable clearable :placeholder="t('sys.messages.sms.log.rules', 'channel')" @change="handleQuery">
              <el-option v-for="channel in channelList" :key="channel.id" :label="channel.signature + `【 ${getDictLabel(DICT_TYPE.SYSTEM_SMS_CHANNEL_CODE, channel.code)}】`" :value="channel.id" />
            </el-select>
          </ElFormItem>
          <ElFormItem :label="t('sys.messages.sms.log', 'templateId')" prop="templateId" class="!w-240px">
            <el-input v-model="queryParams.templateId" :placeholder="t('sys.messages.sms.log.rules', 'templateId')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem v-if="isExpanded" :label="t('sys.messages.sms.log', 'sendStatus')" prop="sendStatus">
            <el-select v-model="queryParams.sendStatus" class="!w-160px" clearable :placeholder="t('sys.messages.sms.log.rules', 'sendStatus')" @change="handleQuery">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_SMS_SEND_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem v-if="isExpanded" :label="t('sys.messages.sms.log', 'sendTime')" prop="sendTime">
            <el-date-picker
              v-model="queryParams.sendTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              clearable
              :start-placeholder="t('common', 'startDate')"
              :end-placeholder="t('common', 'endDate')"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleQuery" />
          </ElFormItem>
          <ElFormItem v-if="isExpanded" :label="t('sys.messages.sms.log', 'receiveStatus')" prop="receiveStatus">
            <el-select v-model="queryParams.receiveStatus" class="!w-160px" clearable :placeholder="t('sys.messages.sms.log.rules', 'receiveStatus')" @change="handleQuery">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_SMS_RECEIVE_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem v-if="isExpanded" :label="t('sys.messages.sms.log', 'receiveTime')" prop="receiveTime">
            <el-date-picker
              v-model="queryParams.receiveTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              clearable
              :start-placeholder="t('common', 'startDate')"
              :end-placeholder="t('common', 'endDate')"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleQuery" />
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action',
              'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset')
            }}</el-button>
            <CButton v-if="checkPermit(['system:dict:type:export'])" type="warning" :disabled="queryLoading" :onClick="handleExport" preIcon="ri:export-line" :title="t('action', 'export')" />
            <CButton text type="info" :disabled="queryLoading" :onClick="expandChange" :preIcon="isExpanded ? 'ep:arrow-up' : 'ep:arrow-down'" :title="isExpanded ? t('action', 'fold') : t('action', 'unfold')" />
          </ElFormItem>
        </ElForm>
      </template>
      <template #content>
        <el-table v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" border>
          <el-table-column prop="id" :label="t('common', 'id')" width="60" align="center" />
          <el-table-column prop="create_time" :label="t('common', 'createTime')" :formatter="dateTimeFormatter" align="center" />
          <el-table-column :label="t('sys.messages.sms.log', 'mobile')" align="center" prop="mobile" width="120">
            <template #default="scope">
              <div>{{ scope.row.mobile }}</div>
              <div v-if="scope.row.userType && scope.row.userId">
                <dict-tag :type="DICT_TYPE.USER_TYPE" :value="scope.row.userType" />
                {{ '(' + scope.row.userId + ')' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="templateContent" :label="t('sys.messages.sms.log', 'templateContent')" align="center" width="300" />
          <el-table-column :label="t('sys.messages.sms.log', 'sendStatus')" align="center" width="180">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_SMS_SEND_STATUS" :value="scope.row.sendStatus" />
              <div>{{ formatDate(scope.row.sendTime) }}</div>
            </template>
          </el-table-column>
          <el-table-column :label="t('sys.messages.sms.log', 'receiveStatus')" align="center" width="180">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_SMS_RECEIVE_STATUS" :value="scope.row.receiveStatus" />
              <div>{{ formatDate(scope.row.receiveTime) }}</div>
            </template>
          </el-table-column>
          <el-table-column :label="t('sys.messages.sms.log', 'channel')" align="center" width="120">
            <template #default="scope">
              <div>
                {{ channelList.find((channel) => channel.id === scope.row.channelId)?.signature }}
              </div>
              <dict-tag :type="DICT_TYPE.SYSTEM_SMS_CHANNEL_CODE" :value="scope.row.channelCode" />
            </template>
          </el-table-column>
          <el-table-column :label="t('sys.messages.sms.log', 'templateId')" align="center" prop="templateId" />
          <el-table-column :label="t('sys.messages.sms.log', 'templateType')" align="center" prop="templateType">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.SYSTEM_SMS_TEMPLATE_TYPE" :value="scope.row.templateType" />
            </template>
          </el-table-column>
          <el-table-column prop="operate" :label="t('common', 'operate')" width="90" align="center" fixed="right">
            <template #default="scope">
              <el-button type="primary" @click="openDetail(scope.row)">{{ t('action', 'detail') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageIndex" :total="total" :disabled="queryLoading" @pagination="getList" />
        <!-- 表单弹窗：详情 -->
        <SmsLogDetail ref="detailRef" />
        <!-- 表单弹窗：导出 -->
        <ExcelExportDialog ref="ExcelExportDialogRef" :filename="t('sys.messages.sms.log', 'manage')" :hasSelected="false" :fieldList="filedList" @success="exportDone" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
